<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Illuminate\Auth\EloquentUserProvider;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JWTToken extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @param array                     $guards
     * @return mixed
     */
    public function handle($request, Closure $next, ...$guards)
    {
        // 检查此次请求中是否带有 token，如果没有则抛出异常。
        $this->checkForToken($request);

        // 使用 try 包裹，以捕捉 token 过期所抛出的 TokenExpiredException  异常
        try {
            $this->auth->parseToken();

            $model = $this->setGuard($guards);
            // 手动验证该token是否与该model绑定 防止拿其他Model的token来验证
            if (!$this->auth->checkSubjectModel($model)) {
                throw new UnauthorizedHttpException('jwt-auth', 'Token is not valid.');
            }

            if ($this->auth->authenticate()) {
                return $next($request);
            }
            throw new UnauthorizedHttpException('jwt-auth', 'User is not login.');

        } catch (TokenExpiredException $exception) {
            try {
                // 刷新用户的 token
                $token = $this->auth->refresh();
                // 使用一次性登录以保证此次请求的成功
                app()->auth->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);

            } catch (JWTException $exception) {
                // 如果捕获到此异常，即代表 refresh 也过期了，用户无法刷新令牌，需要重新登录。
                throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
            }
        } catch (Exception $e) {
            throw new UnauthorizedHttpException('jwt-auth', $e->getMessage());
        }

        // 在响应头中返回新的 token
        return $this->setAuthenticationHeader($next($request), $token);
    }

    /**
     * Set the authentication header.
     *
     * @param  \Illuminate\Http\Response|\Illuminate\Http\JsonResponse  $response
     * @param  string|null  $token
     *
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function setAuthenticationHeader($response, $token = null)
    {
        $token = $token ?: $this->auth->refresh();
        $response->headers->set('New-Token', $token);
        $response->headers->set('Access-Control-Expose-Headers', 'New-Token');

        return $response;
    }

    /**
     * @param $guards
     * @return string
     */
    protected function setGuard($guards)
    {
        // 取得验证的对象
        $guard = $guards[0] ?: config('auth.defaults.guard');
        // 获取provider 和 设置 JWTAuth指定guard
        $provider = config("auth.guards.{$guard}.provider");
        $model = config("auth.providers.{$provider}.model");
        $userProvider = new EloquentUserProvider(app('hash'), $model);
        app()->auth->setProvider($userProvider);

        return $model;
    }
}